﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Text;

namespace Stee.CAP8.MessageBus.Sagas.Core.Common
{
    public static class DataConvert
    {

        public static T ToObject<T>(this byte[] bytes)
        {
            if (bytes == null)
                return default;
            var jsonString = Encoding.UTF8.GetString(bytes);
            if (string.IsNullOrWhiteSpace(jsonString)) 
                return default;
            try
            {
                var obj = JsonConvert.DeserializeObject<T>(jsonString);
                return obj;
            }
            catch (Exception ex)
            {
                return default;
            }
        }

        public static byte[] ObjToBytes(this object obj) 
        {
            if (obj == null) return null;
            var jsonstring = JsonConvert.SerializeObject(obj);
            var bytes = Encoding.UTF8.GetBytes(jsonstring);
            return bytes;
        }
    }
}
